package com.viknix.threadpool.manager.client.template;

import com.viknix.threadpool.manager.client.builder.ThreadFactoryBuilder;
import com.viknix.threadpool.manager.client.builder.ThreadPoolBuilder;
import com.viknix.threadpool.manager.client.util.ValidatorUtil;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: Dongqi
 * @Date: 2021/10/21 18:29
 * @Version 1.0
 * @Description: 线程池模板工具
 */
public abstract class AbstractThreadPoolExecutorTemplate {

    public final ThreadPoolExecutor createThreadPoolExecutor(ThreadPoolBuilder builder) {
        checkParam(builder);
        buildThreadFactory(builder);
        return buildThreadPoolExecutor(builder);
    }

    protected void checkParam(ThreadPoolBuilder builder) {
        ValidatorUtil.requiredParamCheck(builder);
    }

    protected void buildThreadFactory(ThreadPoolBuilder builder) {
        ThreadFactory threadFactory = ThreadFactoryBuilder.builder()
                .setNamePrefix(builder.getThreadNamePrefix())
                .setDaemon(builder.isDaemon())
                .setPriority(builder.getPriority())
                .setThreadFactory(builder.getThreadFactory())
                .build();
        builder.setThreadFactory(threadFactory);
    }

    protected abstract ThreadPoolExecutor buildThreadPoolExecutor(ThreadPoolBuilder builder);
}
